package com.killer.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.killer.dao.OrderMapper;
import com.killer.pojo.Order;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;

    public Order addOrder(){
        Order order=new Order();
        order.setStatus(0);
        orderMapper.insert(order);
        //发送消息到业务队列
        sendOrderMessage(order);
        return order;
    }

    private void sendOrderMessage(Order order){
        //以订单id作为消息体
        String payload=order.getId().toString();
        //设置消息过期时间为10秒
        MessageProperties messageProperties = new MessageProperties();
        //设置消息的编码
        messageProperties.setContentEncoding("utf-8");
        //消息为持久化消息
        messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
        //设置消息过期时间 单位：毫秒
        messageProperties.setExpiration("10000");
        Message message = new Message(payload.getBytes(), messageProperties);
        amqpTemplate.send("ex.biz", "rk.biz", message);
    }

    public Order findOrderById(Long orderId) {
        return orderMapper.selectById(orderId);
    }

    public void updateOrder(Order order) {
        orderMapper.updateById(order);
    }

    public boolean payOrder(Long orderId) {
        //查询订单
        Order order = findOrderById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        //判断是否已经过期被删除了
        if (order.getStatus() == -1) {
            return false;
        }
        //将订单状态改成已支付
        order.setStatus(1);
        updateOrder(order);
        return true;
    }

    public List<Order> listExpireOrders(){
        return orderMapper.selectList(new QueryWrapper<Order>().eq("status", -1).orderByDesc("id"));
    }
}
